﻿using CRM.Admin.Contracts.Contract.Customer;
using CRM.Admin.Contracts.Dto.Customer;
using CRM.Admin.Contracts.Model.Customer;
using KingsSharp.Common;
using KingsSharp.Common.Data;
using KingsSharp.Common.Extensions;
using KingsSharp.Core;
using KingsSharp.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KingsSharp.Core.Data.Entity;

namespace CRM.Admin.Services.Service.Customer
{
    public class CompetitorService : ServiceBase, ICompetitorService
    {
        private IRepository<Competitor, Guid> CompetitorRepository;

        public CompetitorService(IRepository<Competitor, Guid> _CompetitorRepository)
            :base(_CompetitorRepository.UnitOfWork)
        {
            CompetitorRepository = _CompetitorRepository;
        }

        public IQueryable<Competitor> Item
        {
            get
            {
                return CompetitorRepository.Entities;
            }
        }

        public OperationResult Insert(params CompetitorDto[] dtos)
        {
            dtos.CheckNotNull("dtos");
            var result = CompetitorRepository.Insert(dtos, dto => {
                if (Item.Where(a => a.Name == dto.Name&&a.CustomerId==dto.CustomerId).Count() > 0)
                {
                    throw new Exception("竞争对手 “{0}” 已经存在，无法创建"
                            .FormatWith(dto.Name));
                }
            });
            return result;
        }

        public OperationResult Update(params CompetitorDto[] dtos)
        {
            dtos.CheckNotNull("dtos");
            var result = CompetitorRepository.Update(dtos, dto =>
            {
                if (Item.Where(a => a.Name == dto.Name && a.CustomerId == dto.CustomerId&&a.Id != dto.Id).Count() > 0)
                {
                    throw new Exception("竞争对手“{0}” 规则已经存在，竞争对手无法更新"
                            .FormatWith(dto.Name));
                }
            }, (dto, model) => {

                return model;
            });
            return result;
        }

        public OperationResult Delete(params Guid[] ids)
        {
            ids.CheckNotNull("ids");
            int delcount = CompetitorRepository.Delete(a => ids.Contains(a.Id));
            return new OperationResult(OperationResultType.Success, "删除成功");
        }

    }
}
